package com.sumainfor.pc.epc.service.impl;

import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.ParentDeptVo;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.pc.epc.dao.HoHousingAlterInfoMapper;
import com.sumainfor.pc.epc.dao.HoHousingAlterMapper;
import com.sumainfor.pc.epc.dao.HoHousingPlanMapper;
import com.sumainfor.pc.epc.dao.MktFeign.HousingPlanMapper;
import com.sumainfor.pc.epc.dao.UtilsMapper;
import com.sumainfor.pc.epc.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.epc.service.HoHousingAlterService;
import io.netty.util.internal.NoOpTypeParameterMatcher;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.Identifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 房源配置变更
 */
@Service
public class HoHousingAlterServiceImpl implements HoHousingAlterService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(HoHousingAlterServiceImpl.class);
    @Autowired
    private HoHousingAlterMapper hoHousingAlterMapper;
    @Autowired
    private HoHousingPlanMapper hoHousingPlanMapper;
    @Autowired
    private HoHousingAlterInfoMapper hoHousingAlterInfoMapper;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private ZzuulFeign zzuulFeign;
    @Autowired
    private ZpcMktFeign zpcMktFeign;

    @Autowired
    private HousingPlanMapper housingPlanMapper;

    /**
     * 运营部服务管家根据房源配置主表编号查询房源配置变更
     */
    @Override
    public JsonResult getHoHousingAlterList(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        List<Map<String, Object>> alterList = hoHousingAlterMapper.getHoHousingAlterList(params);
        //返回配置变更的列表
        if (alterList != null && alterList.size() > 0) {
            result.superPut("alterList", alterList);
            result.superPut("alterCont", "1");
            result.superPut("errorCode", "0");
        } else {
            //返回房源配置列表
            alterList = hoHousingPlanMapper.getHoHousingPlanList(params);
            if (alterList != null) {
                result.superPut("alterList", alterList);
                result.superPut("alterCont", "0");
                result.superPut("errorCode", "0");
            } else {
                result.putFailed("服务器繁忙");
            }
        }
        return result;
    }

    /**
     * 新增房源配置详表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult addHoHousingAlter(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                //配置变更编号
                String UUID = "";
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "AltId");
                    put("database", Constants.DATA_SOURCE_TCEPC);
                    put("surface", "tcepc_housing_alter");
                }});
                if (uuid != null && (!uuid.get("uuid").toString().equals(""))) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("ha", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("ha", 0);
                }

                //获取当前登录人的服务中心编号
                SysUserVo userVo = ContextUtils.getSysUser();
                ParentDeptVo vo = null;
                for (int i = 0; i < userVo.getLength(); i++) {
                    ParentDeptVo vo1 = userVo.getParentDeptVo();
                    if (vo1.getType().equals(3)) {
                        vo = vo1;
                        break;
                    }
                }

                System.out.println("uuid:" + uuid);
                params.put("AltId", UUID);//配置变更编号
                params.put("HousingType","3");//1.翻修配置 2.原始配置 3.租客配置,
                params.put("LaunchUserId", ContextUtils.getUserId());//发起人
                if (vo!=null){
                    params.put("MiId",vo.getDeptId());//获取发起人所属服务中心编号
                }
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("AuditState", "1");//审核状态   1.审核中   2被驳回    3审核通过
                params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                if (hoHousingAlterMapper.addHoHousingAlter(params) > 0) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("data");
                    //新增的数量
                    List<Map<String, Object>> changeList = (List<Map<String, Object>>) params.get("changeList");
                    System.out.println("changeList：" + changeList);
                    for (int i = 0; i < list.size(); i++) {
                        Map<String, Object> aMap = list.get(i);
                        aMap.put("AltId", params.get("AltId"));
                        aMap.put("HouConId", params.get("HouConId"));
                        aMap.put("HouConName", params.get("HouConName"));
                        aMap.put("instm", params.get("instm"));
                        aMap.put("insterm", params.get("insterm"));
                        aMap.put("insby", params.get("insby"));
                        aMap.put("insfnc", params.get("insfnc"));
                        System.out.println("aMap:"+aMap);
                        hoHousingAlterInfoMapper.addHoHousingAltInfo(aMap);
                    }
//                    //设置参数（新增已有的配置）
//                    Map<String, Object> dataMap = new HashMap<String, Object>();
//                    dataMap.put("ChangeComNumber", "1");
//                    dataMap.put("ComId", "1");
//                    dataMap.put("ComType", "1");
//                    dataMap.put("ComName", "1");
//                    dataMap.put("ComNumber", "1");
//                    dataMap.put("ComPrice", "1");
//                    dataMap.put("ComMonad", "1");
//                    dataMap.put("ComSpeId", "1");
//                    dataMap.put("ComSpeMoId", "1");
//                    dataMap.put("ComSpeMoName", "1");
//                    dataMap.put("ComSpeName", "1");
//                    dataMap.put("HouConId", "1");
//                    dataMap.put("HouConName", "1");
//                    dataMap.put("RealComNumber", "1");
//                    dataMap.put("AltId", "1");
//                    dataMap.put("HouConId", "1");
//                    dataMap.put("HouConId", "1");
//                    dataMap.put("instm", "1");
//                    dataMap.put("insterm", "1");
//                    dataMap.put("insby", "1");
//                    dataMap.put("insfnc", "1");
//                    dataMap.put("hconList", list);
//                    hoHousingAlterInfoMapper.addHoHousingAlterInfo(dataMap);
                    if (changeList.size() > 0) {
                        for (int i = 0; i < changeList.size(); i++) {
                            Map<String, Object> aMap = changeList.get(i);
                            aMap.put("AltId", params.get("AltId"));
                            aMap.put("HouConId", params.get("HouConId"));
                            aMap.put("HouConName", params.get("HouConName"));
                            aMap.put("instm", params.get("instm"));
                            aMap.put("insterm", params.get("insterm"));
                            aMap.put("insby", params.get("insby"));
                            aMap.put("insfnc", params.get("insfnc"));
                            hoHousingAlterInfoMapper.addHoHousingAltInfo(aMap);
                        }
                        //新的配置
//                        Map<String, Object> dataXinMap = new HashMap<String, Object>();
//                        dataXinMap.put("ChangeComNumber", "1");
//                        dataXinMap.put("ComId", "1");
//                        dataXinMap.put("ComType", "1");
//                        dataXinMap.put("ComName", "1");
//                        dataXinMap.put("ComNumber", "1");
//                        dataXinMap.put("ComMonad", "1");
//                        dataXinMap.put("ComSpeId", "1");
//                        dataXinMap.put("ComSpeName", "1");
//                        dataXinMap.put("ComSpeMoId", "1");
//                        dataXinMap.put("ComSpeMoName", "1");
//                        dataXinMap.put("ComPrice", "1");
//                        dataXinMap.put("HouConId", "1");
//                        dataXinMap.put("HouConName", "1");
//                        dataXinMap.put("RealComNumber", "1");
//                        dataXinMap.put("AltId", "1");
//                        dataXinMap.put("HouConId", "1");
//                        dataXinMap.put("instm", "1");
//                        dataXinMap.put("insterm", "1");
//                        dataXinMap.put("insby", "1");
//                        dataXinMap.put("insfnc", "1");
//                        dataXinMap.put("hconList", changeList);
//                        hoHousingAlterInfoMapper.addHoHousingAlterInfo(dataXinMap);
                    }

                    result.putSuccess("操作成功");
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }

        if (result.isSuccess()) {
            //成功
            CustomMap data = CustomMap.create("MeType", 7)
                    .put("Title", "新接收的配置变更单")
                    .put("Content", HtmlUtil.stringToHTML("您收到一条新的房源配置变更单，请及时处理！；", "", Color.blue))
                    .put("by", ContextUtils.getUserId())
                    .put("term", 3);
            zzuulFeign.AddMessage(data);
        }

        return result;
    }

    /**
     * 服务管家查询房间的物品清单
     */
    @Override
    public List<Map<String, Object>> getHoHousingAlterRentList(Map<String, Object> params) {
        List<Map<String, Object>> alterList = hoHousingAlterMapper.getHoHousingAlterRentList(params);
        //返回配置变更的列表
        if (alterList != null && alterList.size() > 0) {
            return alterList;
        } else {
            //返回房源配置列表
            alterList = hoHousingPlanMapper.getHoHousingPlanRentList(params);
        }
        return alterList;
    }

    /**
     * 服务管家查询整租房间的公共区域的物品清单
     */
    @Override
    public List<Map<String, Object>> getHoHousingAlterRentComList(Map<String, Object> params) {
        List<Map<String, Object>> alterList = hoHousingAlterMapper.getHoHousingAlterRentComList(params);
        //返回配置变更的列表
        if (alterList != null && alterList.size() > 0) {
            return alterList;
        } else {
            //返回房源配置列表
            alterList = hoHousingPlanMapper.getHoHousingPlanRentComList(params);
        }
        return alterList;
    }
    /**
     * 查询房源的配置变更列表（服务管家配置变更记录、服务中心经理配置变更记录）
     */
    @Override
    public JsonResult getHoAlterList(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        //获取当前登录人的服务中心编号
        SysUserVo userVo = ContextUtils.getSysUser();
        ParentDeptVo vo = null;
        for (int i = 0; i < userVo.getLength(); i++) {
            ParentDeptVo vo1 = userVo.getParentDeptVo();
            if (vo1.getType().equals(3)) {
                vo = vo1;
                break;
            }
        }
        if (vo!=null){
            params.put("MiId",vo.getDeptId());//获取发起人所属服务中心编号
        }
        //查询配置变更列表
        List<Map<String,Object>> epcList=hoHousingAlterMapper.getHoAlterList(params);
        //保存合同编号列表
        List<String> paidList=new ArrayList<String>();
        //保存发起人编号
        List<String> LaunchUserIdList = new ArrayList<>();
        //保存服务中心编号
        List<String> idList = new ArrayList<>();

        for (Map<String,Object> houConMap: epcList){
            if (houConMap.get("PaId")!=null){
                paidList.add(houConMap.get("PaId").toString());
            }
            if (houConMap.get("LaunchUserId")!=null){
                LaunchUserIdList.add(houConMap.get("LaunchUserId").toString());
            }
            if (houConMap.get("MiId")!=null){
                idList.add(houConMap.get("MiId").toString());
            }
        }
        params.put("paidList",paidList);
        params.put("LaunchUserIdList",LaunchUserIdList);
        //params.put("MiIdList",MiIdList);

        //去网关查询发起人编号和服务中心
        if (idList.size()>0) {
            params.put("idList",idList);
            System.out.println("到网关的参数"+idList);
            JsonResult zuulDeptResult = zzuulFeign.getDeptNameByDeptId(params);
            System.out.println(zuulDeptResult);
            List<Map<String, Object>> DeptList = (List<Map<String, Object>>) zuulDeptResult.get("result");
            if(DeptList.size()>0&&DeptList !=null){
                for (Map<String, Object> map1 : epcList) {
                    if (map1.get("MiId") != null) {
                        for (Map<String, Object> map2 : DeptList) {
                            if (map2.get("dept_id") != null) {
                                if (map1.get("MiId").toString().equals(map2.get("dept_id").toString())) {
                                    map1.putAll(map2);
                                }
                            }
                        }
                    }
                }
            }
        }
        if(LaunchUserIdList.size()>0){
            JsonResult zuulLoginNameResult = zzuulFeign.getLoginNameList(params);
            List<Map<String, Object>> LoginNameList = (List<Map<String, Object>>) zuulLoginNameResult.get("result");
            if (LoginNameList.size()>0&&LoginNameList !=null) {
                for (Map<String, Object> map1 : epcList) {
                    if (map1.get("LaunchUserId") != null) {
                        for (Map<String, Object> map2 : LoginNameList) {
                            if (map2.get("user_id") != null) {
                                if (map1.get("LaunchUserId").toString().equals(map2.get("user_id").toString())) {
                                    map1.putAll(map2);
                                }
                            }
                        }
                    }
                }
            }
        }


        //到市场部查询房源的相关信息
        JsonResult marketResult=zpcMktFeign.getRdAlterList(params);
        if (marketResult.get("errorCode").toString().equals("0")){
            Map<String,Object> maeketMap=(Map<String,Object>)marketResult.get("result");
            List<Map<String,Object>> marketList=(List<Map<String,Object>>)maeketMap.get("dataList");
            for (Map<String,Object> map1:marketList){
                if (map1.get("PaId")!=null){
                    for (Map<String,Object> map2:epcList){
                        if (map2.get("PaId")!=null){
                            if (map1.get("PaId").toString().equals(map2.get("PaId").toString())){
                                map1.putAll(map2);
                            }
                        }
                    }
                }
            }
        }
        return marketResult;
    }
    /**
     * 查询房源的配置变更列表（服务管家配置变更记录、服务中心经理配置变更记录）
     */
    @Override
    public JsonResult getHoAlterListByAltId(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        PageUtils pageUtils = new PageUtils();
        Pager pager=new Pager();

        //获取当前登录人的服务中心编号
        SysUserVo userVo = ContextUtils.getSysUser();
        ParentDeptVo vo = null;
        for (int i = 0; i < userVo.getLength(); i++) {
            ParentDeptVo vo1 = userVo.getParentDeptVo();
            if (vo1.getType().equals(3)) {
                vo = vo1;
                break;
            }
        }
        if (vo!=null){
            params.put("MiId",vo.getDeptId());//获取发起人所属服务中心编号
        }

        pager.setPageno(Integer.parseInt(params.get("pageno").toString()));
        pager.setPagesize(Integer.parseInt(params.get("pagesize").toString()));
        pager.setPagerNecessary(params, pager);
        Integer cout=hoHousingAlterMapper.getHoAlterListCountByAltId(params);
        if(cout==0){
            return pageUtils.getJsonResult(new ArrayList<Map<String,Object>>(), params,cout);
        }
        List<Map<String,Object>>getCommunityList=hoHousingAlterMapper.getHoAlterListByAltId(params);
        result=pageUtils.getJsonResult(getCommunityList, params, cout);
        return result;
    }
    /**
     * 服务中心经理审核房源配置变更
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult updateHoHouAlter(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        if (params.get("AltId")==null || params.get("AuditState")==null){
            return result.putFailed("参数不正确");
        }
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                params.put("SysUserId", ContextUtils.getUserId());//审核人
                params.put("by", params.get("SysUserId"));//操作人
                params.put("term", "3");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                params.put("AuditTime",params.get("updtm"));//审核时间
                Integer count=hoHousingAlterMapper.updateHoHouAlter(params);
                if (count!=null && count==1){
                    result.put("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 查询房源是否有正在审核中的配置变更(服务管家配置变更记录、服务中心经理配置变更记录）
     */
    @Override
    public JsonResult getHoAlterStateByAltId(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        if (params.get("HouConId")==null){
            return result.putFailed("参数不正确");
        }
        //查询房源是否有正在审核中的配置变更
        Integer count=hoHousingAlterMapper.getHoAlterStateByAltId(params);
        if (count!=null){
            result.put(count);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }


    @Override
    public JsonResult getHouConIdPlan(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        return result.put(hoHousingAlterMapper.getHouConIdPlan(params));
    }

    /**
     * 保存变更的房源配置
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addHouConPlan(Map<String, Object> params) {

        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            List<Map<String,Object>> changeList = (List<Map<String, Object>>) params.get("changeList");
            List<Map<String,Object>> data = (List<Map<String, Object>>) params.get("data");

            if (data !=null &&data.size()>0){//先修改房源配置
             for (Map<String,Object> dataMap:data){

            if (MapUtils.getInteger(dataMap,"ComNumber")>0){
                //修改该配置
                dataMap.put("term","3");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                dataMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(dataMap);
               Integer zz= housingPlanMapper.updateHousingPlanInfo(dataMap);
                if (zz>0){
                    result.putSuccess("修改成功");
                }else{
                    return result.putFailed("修改失败");
                }


            }else if (MapUtils.getInteger(dataMap,"ComNumber")<=0){
                Integer ss = housingPlanMapper.deleteHouplanInfo(dataMap);

                if (ss>0){
                    result.putSuccess("删除成功");
                }else{
                    return result.putFailed("删除失败");
                }

            }
             }
            }

            //增加之前先查询配置的状态
            Map<String,Object> HouIdsMapss= hoHousingAlterMapper.getHouIdsMax(params);

            if (changeList !=null &&changeList.size()>0){//增加房源配置

                for (Map<String,Object> aMap: changeList){

                    //增加之前先查询自编号的最大值
                    Map<String,Object> HouIdsMap= hoHousingAlterMapper.getHouIdsMax(params);
                    Integer HouConIdsMax = MapUtils.getInteger(HouIdsMap,"HouConIdsMax");

                    aMap.put("PalHouId", params.get("PalHouId"));
                    aMap.put("HouConIds", HouConIdsMax+1);
                    aMap.putAll(HouIdsMapss);
                    aMap.put("term","3");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    aMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(aMap);
                    Integer a = housingPlanMapper.AddHousingPlanInfo(aMap);
                    if (a>0){
                        result.putSuccess("新增成功");
                    }else{
                         return result.putFailed("新增失败");
                    }
                }
            }
            //操作完成之后,查询房源现有配置.如果有智能电表的存在,将房源出租类型修改为智能的,如果没有就修改为无
            List<Map<String,Object>> mapList = hoHousingAlterMapper.getHouConIdPlan(params);
            Integer Payment = new Integer("0");
            if (mapList.size()>0){//如果
                for (Map<String,Object> mapone:mapList){
                    if (MapUtils.getInteger(mapone,"ComType")==4&&(MapUtils.getInteger(mapone,"Intelligent")==0||MapUtils.getInteger(mapone,"Intelligent")==1)){
                        Payment++;
                    }
                }
            }

            if (Payment>0){
                //修改房源
                params.put("Payment",0);

            }else if(Payment==0){
                //修改房源
                params.put("Payment",1);
            }

            JsonResult MktResult= zpcMktFeign.updatePayment(params);
            System.out.println("MktResult"+MktResult);


           if(MktResult.get("errorCode").equals("0")&&MktResult.get("errorCode")!=null){


               result.putSuccess("修改房源表成功");

        }else{
               return result.putFailed("修改房源表失败");
           }

            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        finally {
            lock.unlock();
        }
        return result;

    }

}
